package org.jmeter.tcp.util;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/11/20 15:48
 * @since
 */
public class ByteUtils {

    /**
     * 将二进制转换为16进制的字符串
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 反转字节数组
     * @param bytes
     * @return
     */
    public static byte[] reverse(byte[] bytes) {
        int len = bytes.length;
        byte[] bs = new byte[len];
        for (int index = 0; index < len; index ++) {
            bs[len - index - 1] = bytes[index];
        }
        return bs;
    }

    /**
     * 将int转换为byte数组
     * @param num
     * @param len
     * @return
     */
    public static byte[] int2Bytes(int num, int len) {
        if (len <= 3 && num > ((1 << (len * 8)) - 1)) {
            throw new RuntimeException(String.format("transform int to byte[] fail, int must be less than or equal to %s, but %s", (1 << (len * 8) - 1), num));
        }
        byte[] bytes = new byte[len];
        for (int index = len - 1; index >= 0; index --) {
            bytes[index] = (byte) ((num >> ((len - index - 1) * 8)) & 0xff);
        }
        return bytes;
    }

    /**
     * 16进制byte数组转10进制int
     * @example input: 0x03 0xd2 0xa6 0x8f, output: 64136847
     * @param bytes 16进制byte数组
     * @return 数字
     */
    public static int bytes2Int(byte... bytes) {
        if (bytes.length > 4) {
            throw new RuntimeException(String.format("transform byte to int fail, byte array length must less than or equal to 4, but %s", bytes.length));
        }
        int num = 0;
        for (byte b : bytes) {
            num <<= 8;
            num |= b & 0xff;
        }
        return num;
    }

}
